<script setup>
import {ref, onMounted, getCurrentInstance} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const advertisers = ref([]) // 广告主列表
const advertisersMap = ref({}) // 广告主映射表，用于优化查找
const { proxy } = getCurrentInstance()

// 是否显示回收站
const showRecycleBin = ref(false)

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增广告计划')
const formMode = ref('add') // add or edit

// 表单数据
const form = ref({
  campaignId: '',
  advertiserId: '',
  campaignName: '',
  startTime: '',
  endTime: '',
  budget: '',
  targetAudience: {
    age_range: [],
    gender: '',
    interests: []
  },
  status: 'draft'
})

// 表单规则
const rules = {
  advertiserId: [
    { required: true, message: '请选择广告主', trigger: 'change' }
  ],
  campaignName: [
    { required: true, message: '请输入广告计划名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  budget: [
    { required: true, message: '请输入预算', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
  ]
}

// 状态选项
const statusOptions = [
  { label: '草稿', value: 'draft' },
  { label: '运行中', value: 'running' },
  { label: '已暂停', value: 'paused' },
  { label: '已完成', value: 'completed' }
]

// 兴趣标签选项
const interestOptions = [
  { label: '体育', value: 'sports' },
  { label: '科技', value: 'tech' },
  { label: '娱乐', value: 'entertainment' },
  { label: '美食', value: 'food' },
  { label: '旅游', value: 'travel' }
]

// 模拟数据
const mockCampaigns = [
  {
    campaignId: 1,
    advertiserId: 1,
    campaignName: '夏季促销活动',
    startTime: '2024-06-01 00:00:00',
    endTime: '2024-08-31 23:59:59',
    budget: 50000.00,
    targetAudience: JSON.stringify({
      age_range: ['18-24', '25-34'],
      gender: 'all',
      interests: ['sports', 'tech']
    }),
    status: 'running'
  },
  {
    campaignId: 2,
    advertiserId: 2,
    campaignName: '新品发布会',
    startTime: '2024-07-01 00:00:00',
    endTime: '2024-07-31 23:59:59',
    budget: 30000.00,
    targetAudience: JSON.stringify({
      age_range: ['25-34', '35-44'],
      gender: 'female',
      interests: ['fashion', 'entertainment']
    }),
    status: 'draft'
  },
  {
    campaignId: 3,
    advertiserId: 1,
    campaignName: '双11大促',
    startTime: '2024-11-01 00:00:00',
    endTime: '2024-11-11 23:59:59',
    budget: 100000.00,
    targetAudience: JSON.stringify({
      age_range: ['18-24', '25-34', '35-44'],
      gender: 'all',
      interests: ['shopping', 'tech', 'entertainment']
    }),
    status: 'paused'
  }
];

const mockAdvertisers = [
  {
    advertiserId: 1,
    companyName: '示例公司1',
    contactPerson: '张三',
    contactPhone: '13800138001',
    contactEmail: 'zhangsan@example.com'
  },
  {
    advertiserId: 2,
    companyName: '示例公司2',
    contactPerson: '李四',
    contactPhone: '13800138002',
    contactEmail: 'lisi@example.com'
  }
];

// 获取广告计划列表
const getCampaignsList = async () => {
  loading.value = true;
  try {
    const url = showRecycleBin.value ? '/campaigns/deleted' : '/campaigns';
    const result = await request.get(url, {
      params: {
        page: pagination.value.currentPage,
        size: pagination.value.pageSize
      }
    });
    console.log(result);
    tableData.value = result.data.records;
    pagination.value.total = result.data.total;
  } catch (error) {
    console.error('获取数据失败:', error);
    tableData.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取广告主列表
const getAdvertisersList = async () => {
  try {
    const result = await request.get('/advertisers');
    // 确保返回的数据是数组
    const advertiserList = result.data.records || result.data || [];
    // 过滤掉无效数据
    advertisers.value = advertiserList.filter(item => item && item.advertiserId);
    // 只为有效数据创建映射
    advertisersMap.value = Object.fromEntries(
      advertisers.value.map(advertiser => [advertiser.advertiserId, advertiser])
    );
  } catch (error) {
    console.error('获取广告主列表失败:', error);
    advertisers.value = [];
    advertisersMap.value = {};
  }
};

// 打开新增对话框
const handleAdd = () => {
  getAdvertisersList();
  formMode.value = 'add'
  dialogTitle.value = '新增广告计划'
  form.value = {
    campaignId: '',
    advertiserId: '',
    campaignName: '',
    startTime: '',
    endTime: '',
    budget: '',
    targetAudience: {
      age_range: [],
      gender: '',
      interests: []
    },
    status: 'draft'
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  formMode.value = 'edit'
  dialogTitle.value = '编辑广告计划'
  form.value = {
    ...row,
    targetAudience: typeof row.targetAudience === 'string'
      ? JSON.parse(row.targetAudience)
      : row.targetAudience
  }
  dialogVisible.value = true
}

// 删除广告计划
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该广告计划吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/campaigns/${row.campaignId}`);
      ElMessage.success('删除成功');
      getCampaignsList();
    } catch (error) {
      // 错误已经被 request 拦截器处理
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    const method = formMode.value === 'add' ? 'post' : 'put';
    const url = formMode.value === 'add'
      ? '/campaigns'
      : `/campaigns/${form.value.campaignId}`;

    const submitData = {
      ...form.value,
      targetAudience: JSON.stringify(form.value.targetAudience)
    };

    await request[method](url, submitData);
    ElMessage.success(formMode.value === 'add' ? '新增成功' : '编辑成功');
    dialogVisible.value = false;
    getCampaignsList();
  } catch (error) {
    // 错误已经被 request 拦截器处理
  }
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    draft: '草稿',
    running: '运行中',
    paused: '已暂停',
    completed: '已完成'
  }
  return statusMap[status] || status
}

// 处理页码改变
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  getCampaignsList();
};

// 处理每页条数改变
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  getCampaignsList();
};

// 一键完成广告计划
const handleComplete = async (row) => {
  try {
    await request.put(`/campaigns/${row.campaignId}`, {
      ...row,
      status: 'completed'
    });
    ElMessage.success('广告计划已完成');
    getCampaignsList();
  } catch (error) {
    // 错误已经被 request 拦截器处理
  }
}

// 一键开始广告计划
const handleStart = async (row) => {
  try {
    await request.put(`/campaigns/${row.campaignId}`, {
      ...row,
      status: 'running'
    });
    ElMessage.success('广告计划已开始运行');
    getCampaignsList();
  } catch (error) {
    // 错误已经被 request 拦截器处理
  }
}

// 一键暂停广告计划
const handlePause = async (row) => {
  try {
    await request.put(`/campaigns/${row.campaignId}`, {
      ...row,
      status: 'paused'
    });
    ElMessage.success('广告计划已暂停');
    getCampaignsList();
  } catch (error) {
    // 错误已经被 request 拦截器处理
  }
}

// 切换回收站显示
const toggleRecycleBin = () => {
  showRecycleBin.value = !showRecycleBin.value;
  pagination.value.currentPage = 1;
  getCampaignsList();
};

onMounted(() => {
  getCampaignsList()
  // getAdvertisersList()
})
</script>

<template>
  <div class="campaigns-manage">
    <div class="header">
      <h2>广告计划管理</h2>
      <div class="header-buttons">
        <el-button
          :type="showRecycleBin ? 'primary' : 'default'"
          @click="toggleRecycleBin"
        >
          <el-icon><Delete /></el-icon>
          回收站
        </el-button>
        <el-button
          v-if="!showRecycleBin"
          type="primary"
          @click="handleAdd"
        >新增广告计划</el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column prop="campaignId" label="ID" width="80" />
      <el-table-column prop="campaignName" label="计划名称" />
      <el-table-column label="广告主">
        <template #default="{ row }">
          {{ row.advertiser ?.companyName || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="开始日期" width="180">
        <template #default="{ row }">
          {{ $formatDate(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endDate" label="结束日期" width="180">
        <template #default="{ row }">
          {{ $formatDate(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="budget" label="预算">
        <template #default="{ row }">
          ¥{{ row.budget }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'running' ? 'success' : 'info'">
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <template v-if="!showRecycleBin">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button
              v-if="['draft', 'paused'].includes(row.status)"
              type="success"
              link
              @click="handleStart(row)"
            >开始</el-button>
            <el-button
              v-if="row.status === 'running'"
              type="warning"
              link
              @click="handlePause(row)"
            >暂停</el-button>
            <el-button
              v-if="row.status !== 'completed'"
              type="success"
              link
              @click="handleComplete(row)"
            >完成</el-button>
            <el-button
              v-if="row.status === 'completed'"
              type="danger"
              link
              @click="handleDelete(row)"
            >删除</el-button>
          </template>
          <template v-else>
            <span class="text-gray-500">已删除</span>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="广告主" prop="advertiserId">
          <el-select v-model="form.advertiserId" placeholder="请选择广告主" style="width: 100%">
            <el-option
              v-for="item in advertisers"
              :key="item.advertiserId"
              :label="item.companyName"
              :value="item.advertiserId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划名称" prop="campaignName">
          <el-input v-model="form.campaignName" placeholder="请输入广告计划名称" />
        </el-form-item>
        <el-form-item label="投放时间">
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="预算" prop="budget">
          <el-input-number
            v-model="form.budget"
            :precision="2"
            :step="100"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="目标受众">
          <el-form-item label="年龄范围" label-width="80px">
            <el-select
              v-model="form.targetAudience.age_range"
              multiple
              placeholder="请选择年龄范围"
              style="width: 100%"
            >
              <el-option label="18-24岁" value="18-24" />
              <el-option label="25-34岁" value="25-34" />
              <el-option label="35-44岁" value="35-44" />
              <el-option label="45岁以上" value="45+" />
            </el-select>
          </el-form-item>
          <el-form-item label="性别" label-width="80px">
            <el-radio-group v-model="form.targetAudience.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
              <el-radio label="all">不限</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="兴趣标签" label-width="80px">
            <el-select
              v-model="form.targetAudience.interests"
              multiple
              placeholder="请选择兴趣标签"
              style="width: 100%"
            >
              <el-option
                v-for="item in interestOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.campaigns-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.text-center {
  text-align: center;
}

.text-gray-500 {
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
